package com.example.coursedesign.ui.home;

import android.app.Dialog;
import android.content.Context;
import android.graphics.Paint;
import android.os.Bundle;
import android.os.Handler;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.NumberPicker;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.DialogFragment;
import com.google.android.material.bottomsheet.BottomSheetDialogFragment;

import com.example.coursedesign.R;

import java.lang.reflect.Field;

public class CurrentDosageUnitPicker extends BottomSheetDialogFragment {

    private static final String[] units = {"片", "粒", "mg", "ml", "支", "包"};
    private OnUnitSelectedListener mListener;
    private int defaultUnitIndex = 0; // 默认值
    private Handler mHandler = new Handler();
    private Runnable mScrollRunnable;
    private boolean isScrolling = false;

    public interface OnUnitSelectedListener {
        void onUnitCurrentMedicineSelected(String unit);
    }

    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        return inflater.inflate(R.layout.bottom_sheet_dosage_unit_picker, container, false);
    }

    @Override
    public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);

        NumberPicker numberPicker = view.findViewById(R.id.numberPicker_units);
        Button confirmButton = view.findViewById(R.id.button_confirm);
        Button cancelButton = view.findViewById(R.id.button_cancel); // 假设你有一个取消按钮

        numberPicker.setMinValue(0);
        numberPicker.setMaxValue(units.length - 1);
        numberPicker.setDisplayedValues(units);
        numberPicker.setValue(defaultUnitIndex); // 设置默认选择项
        numberPicker.setWrapSelectorWheel(true);

        // 设置 NumberPicker 字体大小
        setNumberPickerTextSize(numberPicker, 26); // 设置字体大小为 36sp

        // 监听 NumberPicker 的值变化事件
        numberPicker.setOnValueChangedListener((picker, oldVal, newVal) -> {
            if (isScrolling) {
                mHandler.removeCallbacks(mScrollRunnable);
                mScrollRunnable = () -> {
                    isScrolling = false;
                    picker.setValue(newVal); // 确保值正确设置
                };
                mHandler.postDelayed(mScrollRunnable, 2000); // 添加 200ms 的延迟
            }
            isScrolling = true;
        });

        // 确保仅在点击“确定”按钮时触发回调
        confirmButton.setOnClickListener(v -> {
            if (mListener != null) {
                int selectedValue = numberPicker.getValue();
                mListener.onUnitCurrentMedicineSelected(units[selectedValue]);
            }
            dismiss();
        });

        // 取消按钮逻辑
        cancelButton.setOnClickListener(v -> dismiss());
    }

    private void setNumberPickerTextSize(NumberPicker numberPicker, float textSizeSp) {
        try {
            Field selectorWheelPaintField = NumberPicker.class.getDeclaredField("mSelectorWheelPaint");
            selectorWheelPaintField.setAccessible(true);
            Object selectorWheelPaint = selectorWheelPaintField.get(numberPicker);
            if (selectorWheelPaint instanceof Paint) {
                ((Paint) selectorWheelPaint).setTextSize(textSizeSp * getResources().getDisplayMetrics().scaledDensity);
            }

            numberPicker.invalidate();
        } catch (NoSuchFieldException | IllegalAccessException e) {
            e.printStackTrace();
        }
    }

    @Override
    public void onAttach(@NonNull Context context) {
        super.onAttach(context);
        if (context instanceof OnUnitSelectedListener) {
            mListener = (OnUnitSelectedListener) context;
        } else {
            throw new RuntimeException(context.toString() + " must implement OnUnitSelectedListener");
        }

        // 从 Bundle 中获取传递的参数
        if (getArguments() != null) {
            defaultUnitIndex = getArguments().getInt("defaultUnitIndex", 0);
        }
    }

    @Override
    public void onDetach() {
        super.onDetach();
        mListener = null;
    }

    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setStyle(BottomSheetDialogFragment.STYLE_NORMAL, R.style.CustomBottomSheetDialogTheme);
    }

    // 提供一个公共静态方法来获取 units 数组
    public static String[] getUnits() {
        return units;
    }
}